<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="付款人" prop="paymentPerson">
        <el-input
          v-model="queryParams.paymentPerson"
          placeholder="请输入付款人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款单位" prop="paymentUnit">
        <el-select
          v-model="queryParams.paymentUnit"
          placeholder="付款单位"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.customerName"
            :value="customer.customerId"
            :label="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款人" prop="receivePerson">
        <el-input
          v-model="queryParams.receivePerson"
          placeholder="请输入收款人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款单位" prop="receiveUnit">
        <el-select
          v-model="queryParams.receiveUnit"
          placeholder="收款单位"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="customer in customerList_r"
            :key="customer.customerName"
            :value="customer.customerId"
            :label="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="付款金额" prop="paymentAmount">
        <el-input
          v-model="queryParams.paymentAmount"
          placeholder="请输入付款金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款时间" prop="paymentTime">
        <el-date-picker clearable
          v-model="queryParams.paymentTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择付款开始时间">
        </el-date-picker>
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择付款结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:payment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:payment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:payment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:payment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paymentList" @selection-change="handleSelectionChange" border>
      <el-table-column :selectable="selectable" type="selection" width="55" align="center" />
      <el-table-column label="付款记录ID" align="center" prop="paymentRecordId" v-if="false" />
      <el-table-column label="付款人" align="center" prop="paymentPerson" />
      <el-table-column label="付款单位" align="center" prop="paymentUnit" :formatter="unitFormatter" />
      <el-table-column label="收款人" align="center" prop="receivePerson" />
      <el-table-column label="收款单位" align="center" prop="receiveUnit" :formatter="unitFormatter" />
      <el-table-column label="付款金额" align="center" prop="paymentAmount" />
      <el-table-column label="付款时间" align="center" prop="paymentTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span v-if="scope.row.operation">
          </span>
          <span v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['purchase:payment:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['purchase:payment:remove']"
            >删除</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改付款记录
对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="付款人" prop="paymentPerson">
          <el-input v-model="form.paymentPerson" placeholder="请输入付款人" />
        </el-form-item>
        <el-form-item label="付款单位" prop="paymentUnit">
          <el-select v-model="form.paymentUnit" placeholder="请选择单位" @change="selectCustomer">
            <el-option
              v-for="customer in customerList"
              :key="customer.customerName"
              :value="customer.customerId"
              :label="customer.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款人" prop="receivePerson">
          <el-input v-model="form.receivePerson" placeholder="请输入收款人" />
        </el-form-item>
        <el-form-item label="收款单位" prop="receiveUnit">
          <el-select v-model="form.receiveUnit" placeholder="请选择单位" @change="selectCustomerR">
            <el-option
              v-for="customer in customerList_r"
              :key="customer.customerName"
              :value="customer.customerId"
              :label="customer.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款金额" prop="paymentAmount">
          <el-input v-model="form.paymentAmount" placeholder="请输入付款金额">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="付款时间" prop="paymentTime">
          <el-date-picker clearable
            v-model="form.paymentTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择付款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPayment, listAll, getPayment, delPayment, addPayment, updatePayment } from "@/api/purchase/payment";
import { listCustomer } from "@/api/base/customer";
import * as math from 'mathjs'

export default {
  name: "Payment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      paymentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paymentPerson: null,
        paymentUnit: null,
        receivePerson: null,
        receiveUnit: null,
        paymentAmount: null,
        paymentTime: null,
      },
      // 表单参数
      form: {},
      customerList: [],
      customerList_r: [],
      // 表单校验
      rules: {
        receiveUnit: [
          { required: true, message: "收款单位不能为空", trigger: "blur" }
        ],
        paymentUnit: [
          { required: true, message: "付款单位不能为空", trigger: "blur" }
        ],
        paymentAmount: [
          { required: true, message: "付款金额不能为空", trigger: "blur" },
          { pattern: /^-*\d+[.]?\d{0,2}$/, message: '付款金额必须为整数或小数保留两位', trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询付款记录
列表 */
    getList() {
      this.loading = true;
      listPayment(this.queryParams).then(response => {
        this.paymentList = response.rows;
        this.total = response.total;
        this.loading = false;
        if(this.queryParams.pageSize > response.rows.length || this.queryParams.pageNum * this.queryParams.pageSize == response.total) {
          var total = {}
          const query = { ...this.queryParams }
          Reflect.deleteProperty(query, 'pageNum')
          Reflect.deleteProperty(query, 'pageSize')
          listAll(query).then(response => {
            var prev = math.bignumber(0)
            response.forEach(function(item, index) {
              const value = Number(item.paymentAmount);
              if (!isNaN(value)) {
                prev = math.add(prev, value)
              }
            })
            total.paymentAmount = math.number(prev)
            total.operation = true
            total.paymentPerson = '总计'
            this.paymentList.push(total)
          });
        } else {
          var total = {}
          var prev = math.bignumber(0)
          response.rows.forEach(function(item, index) {
            const value = Number(item.paymentAmount);
            if (!isNaN(value)) {
              prev = math.add(prev, value)
            }
          })
          total.paymentAmount = math.number(prev)
          total.operation = true
          total.paymentPerson = '本页小计'
          this.paymentList.push(total)
        }
      });
      var customerParam = { customerType: 0}
      listCustomer(customerParam).then(response => {
        this.customerList = response.rows;
      });
      customerParam.customerType = 2
      listCustomer(customerParam).then(response => {
        this.customerList_r = response.rows;
      });
    },
    selectable(row, index) {
      if(row.operation) {
        return false
      } else {
        return true
      }
    },
    unitFormatter(row, column) {
      var res
      if(column.property == 'paymentUnit') {
        this.customerList.find(function(item) {
          if(item.customerId == parseInt(row.paymentUnit)) {
            res = item.customerName
          }
        })
      } else {
        this.customerList_r.find(function(item) {
          if(item.customerId == parseInt(row.receiveUnit)) {
            res = item.customerName
          }
        })
      }
      return res;
    },
    selectCustomer(value) {
    },
    selectCustomerR(value) {
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paymentRecordId: null,
        paymentPerson: null,
        paymentUnit: null,
        receivePerson: null,
        receiveUnit: null,
        paymentAmount: null,
        paymentTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.paymentRecordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const paymentRecordId = row.paymentRecordId || this.ids
      getPayment(paymentRecordId).then(response => {
        this.form = response.data;
        var paymentUnit, receiveUnit;
        this.customerList.find(function(item) {
          if(item.customerId == parseInt(response.data.paymentUnit)) {
            paymentUnit = item.customerName
          }
        })
        this.customerList_r.find(function(item) {
          if(item.customerId == parseInt(response.data.receiveUnit)) {
            receiveUnit = item.customerName
          }
        })
        this.form.paymentUnit = paymentUnit;
        this.form.receiveUnit = receiveUnit
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.paymentRecordId != null) {
            updatePayment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPayment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paymentRecordIds = row.paymentRecordId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + paymentRecordIds + '"的数据项？').then(function() {
        return delPayment(paymentRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/payment/export', {
        ...this.queryParams
      }, `payment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
